package com.ipCount;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

public class ipCountServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置响应类型
        resp.setContentType("text/html");
        resp.setCharacterEncoding("utf-8");

        ServletContext servletContext = req.getServletContext();
        //设置IpCount Map 键为String 值为Integer
        Map<String, Integer> ipCount = (Map<String, Integer>) servletContext.getAttribute("ipCount");

        // 实际的逻辑是在这里
        PrintWriter out = resp.getWriter();
        out.println("<h1>分IP统计网站浏览次数</h1>");
        for(String ip:ipCount.keySet()) {
            System.out.println(ip + "访问了" +ipCount.get(ip) +"次");
            out.print(ip + ":");
            out.print("次数" + ipCount.get(ip));
            out.println("</br>");
        }
    }

}
